package avicit.bdp.dcs.semistructure.rest;

import avicit.bdp.dcs.Constant;
import avicit.bdp.dcs.semistructure.dto.TemplateDTO;
import avicit.bdp.dcs.semistructure.utils.Constants;
import avicit.platform6.core.rest.msg.ResponseMsg;
import com.alibaba.fastjson2.JSONObject;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;

import static org.junit.Assert.assertEquals;

public class TemplateRestTest {

    public static final String USER_NAME = "avicit2015";
    public static final String PASS_WORD = "avicit2015";
    public static final String HTTP_OK = "200";
    public static final String URL_PREFIX = Constant.HOSTPORT + "/api/bdp/dcs/template/TemplateRest/";
    private String fileName;

    @Before
    public void setUp() throws Exception {
        // 创建模板文件
        fileName = "template_" + System.currentTimeMillis() + ".csv";
        File file = new File(System.getProperty("user.dir") + "/" + fileName);
        if(!file.exists()){
            file.createNewFile();
        }
        FileWriter fileWriter = new FileWriter(file.getName(), true);
        fileWriter.write("name,age,work");
        fileWriter.close();
        System.out.println("文件创建成功！");
    }

    @After
    public void tearDown() throws Exception {
        // 删除模板文件
        File file = new File(System.getProperty("user.dir") + "/" + fileName);
        file.delete();
        System.out.println("删除文件成功！");
    }

    @Test
    public void uploadTemplate() {
        RestTemplate restTemplate  = new RestTemplateBuilder().basicAuthentication(USER_NAME, PASS_WORD).build();
        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("multipart/form-data");
        headers.setContentType(type);
        //设置请求体，注意是LinkedMultiValueMap
        FileSystemResource fileSystemResource = new FileSystemResource(System.getProperty("user.dir")+"/"+fileName);
        MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
        form.add("file", fileSystemResource);
        form.add("filename",fileName);
        //用HttpEntity封装整个请求报文
        HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(form, headers);
        ResponseMsg result = restTemplate.postForObject(URL_PREFIX + "upload", files, ResponseMsg.class);
        assertEquals(HTTP_OK, result.getRetCode());
        System.out.println(result.getResponseBody().toString());
    }

    @Test
    public void saveTemplate() {
        RestTemplate restTemplate  = new RestTemplateBuilder().basicAuthentication(USER_NAME, PASS_WORD).build();
        ResponseEntity<ResponseMsg> result = restTemplate.postForEntity(URL_PREFIX + "createTemplate",
                buildSaveTemplateParas(
                "test","liubftest.csv"), ResponseMsg.class);
        assertEquals("200", result.getBody().getRetCode());
    }

    private HttpEntity<String> buildSaveTemplateParas(String remark, String templateName) {
        TemplateDTO templateDTO = new TemplateDTO();
        templateDTO.setRemark(remark);
        templateDTO.setColumnRule("[{\"name\":\"name\",\"type\":\"TEXT\"},{\"name\":\"age\",\"type\":\"TEXT\"},{\"name\":\"work\",\"type\":\"TEXT\"}]");
        templateDTO.setTemplateName(templateName);
        templateDTO.setFileType(2);
        templateDTO.setFileSeparator(",");

        String param = JSONObject.toJSONString(templateDTO);
        HttpHeaders headers = new HttpHeaders(); // 创建一个头部对象
        headers.setContentType(MediaType.valueOf("application/json; charset=UTF-8"));
        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8.toString());
        headers.add ("Authorization", "Basic " +
                Base64.getUrlEncoder().encodeToString((Constants.DCS_USERNAME + ":" + Constants.DCS_PASSWORD).getBytes()));
        return new HttpEntity<>(param, headers);
    }

    /**
     * 分页查询模板列表
     */
    @Test
    public void getTemplateListByPage() {
        RestTemplate restTemplate  = new RestTemplateBuilder().basicAuthentication(USER_NAME, PASS_WORD).build();
        ResponseEntity<ResponseMsg> result = restTemplate.getForEntity(URL_PREFIX + "getTemplateList?" +
                        "sort=1&templateName=&pageNo=1&pageSize=10", ResponseMsg.class);
        System.out.println(result);
        ResponseMsg body = result.getBody();
        Map<String, Object> responseBody = (Map<String, Object>) body.getResponseBody();
        List list = (List) responseBody.get("result");
        System.out.println("模板个数为：" + list.size());
        assertEquals(HTTP_OK, result.getBody().getRetCode());
    }

    /**
     * 查询所有模板
     */
    @Test
    public void getTemplateList() {
        RestTemplate restTemplate  = new RestTemplateBuilder().basicAuthentication(USER_NAME, PASS_WORD).build();
        ResponseEntity<ResponseMsg> result = restTemplate.getForEntity(URL_PREFIX + "getTemplateListByName", ResponseMsg.class);
        System.out.println(result);
        ResponseMsg body = result.getBody();
        List<TemplateDTO> list = (List<TemplateDTO>) body.getResponseBody();
        System.out.println("模板个数为：" + list.size());
        assertEquals(HTTP_OK, result.getBody().getRetCode());
    }

    @Test
    public void updateTemplate() {
        RestTemplate restTemplate  = new RestTemplateBuilder().basicAuthentication(USER_NAME, PASS_WORD).build();
        ResponseEntity<ResponseMsg> result = restTemplate.postForEntity(URL_PREFIX + "updateTemplate", buildUpdateTemplateParas(
                "4028809b7520ce4e017520d6a2b9000b", "test","123.csv"), ResponseMsg.class);
        assertEquals("200", result.getBody().getRetCode());
    }

    private HttpEntity<String> buildUpdateTemplateParas(String templateId, String remark, String templateName) {
        TemplateDTO templateDTO = new TemplateDTO();
        templateDTO.setId(templateId);
        templateDTO.setRemark(remark);
        templateDTO.setColumnRule("[{\"name\":\"name\",\"type\":\"TEXT\"},{\"name\":\"age\",\"type\":\"TEXT\"},{\"name\":\"work\",\"type\":\"TEXT\"}]");
        templateDTO.setTemplateName(templateName);
        templateDTO.setFileType(2);
        templateDTO.setFileSeparator(",");

        String param = JSONObject.toJSONString(templateDTO);
        HttpHeaders headers = new HttpHeaders(); // 创建一个头部对象
        headers.setContentType(MediaType.valueOf("application/json; charset=UTF-8"));
        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8.toString());
        headers.add ("Authorization", "Basic " +
                Base64.getUrlEncoder().encodeToString((Constants.DCS_USERNAME + ":" + Constants.DCS_PASSWORD).getBytes()));
        return new HttpEntity<>(param, headers);
    }

    @Test
    public void downloadTemplate() {
        RestTemplate restTemplate  = new RestTemplateBuilder().basicAuthentication(USER_NAME, PASS_WORD).build();
        HttpHeaders headers = new HttpHeaders();
        List list = new ArrayList<>();
        list.add(MediaType.valueOf("application/json"));
        headers.setAccept(list);
        ResponseEntity<byte[]> response = restTemplate.exchange(URL_PREFIX + "downloadTemplate?templateId" +
                        "=4028809b750b73a101750bf352970002", HttpMethod.GET, new HttpEntity<byte[]>(headers),
                byte[].class);
        assertEquals(HTTP_OK, response.getStatusCode().value()+"");
        System.out.println(new String(response.getBody()));
    }

    @Test
    public void deleteTemplateByIds() {
        RestTemplate restTemplate  = new RestTemplateBuilder().basicAuthentication(USER_NAME, PASS_WORD).build();
        ResponseEntity<ResponseMsg> result = restTemplate.exchange(URL_PREFIX + "deleteTemplateByIds?id=4028809b7520ecb3017520f4cab8001a",
                HttpMethod.DELETE, buildDeleteTemplateParas("4028809b7520ecb3017520f4cab8001a"), ResponseMsg.class);
        assertEquals(HTTP_OK, result.getBody().getRetCode());
    }

    private HttpEntity<String> buildDeleteTemplateParas(String id) {
        TemplateDTO templateDTO = new TemplateDTO();
        templateDTO.setId(id);
        String param = JSONObject.toJSONString(templateDTO);
        HttpHeaders headers = new HttpHeaders(); // 创建一个头部对象
        headers.setContentType(MediaType.valueOf("application/json; charset=UTF-8"));
        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8.toString());
        headers.add ("Authorization", "Basic " +
                Base64.getUrlEncoder().encodeToString((Constants.DCS_USERNAME + ":" + Constants.DCS_PASSWORD).getBytes()));
        return new HttpEntity<>(param, headers);
    }
}
